package com.ccteam.shared.domain

import androidx.paging.PagingData
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flowOn

/**
 * @author Xiaoc
 * @since 2021/2/15
 */
abstract class PagingUseCase<in Parameters,Result: Any>(
    private val dispatcher: CoroutineDispatcher
) {

    @ExperimentalCoroutinesApi
    operator fun invoke(parameters: Parameters): Flow<PagingData<Result>> {
        return execute(parameters)
            .catch {
                emit(PagingData.empty())
            }
            .flowOn(dispatcher)
    }

    /**
     * 真正执行的方法，也是需要重写的方法
     * 在该方法里你需要从 Repository 请求数据
     * 然后进行对应转换
     *
     * @param parameters 需要给 Repository 传递的参数
     */
    abstract fun execute(parameters: Parameters): Flow<PagingData<Result>>
}